package com.schoolinfo.action;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.schoolinfo.dao.UserDAO;
import com.schoolinfo.model.User;
import com.schoolinfo.util.DigestUtil;

public class UserAction extends ActionSupport {
	  private static final Logger log = LoggerFactory.getLogger(UserAction.class);
		
	private UserDAO userDAO;
	private String email;
	private String password;
	private String phone;
	private String qq;
	private String rePassword;
	private String name;
	private String newPassword;
	
	private boolean isError=false;
	private String errorMsg="";
	
	

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public boolean isError() {
		return isError;
	}

	public void setError(boolean isError) {
		this.isError = isError;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getRePassword() {
		return rePassword;
	}

	public void setRePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getrePassword() {
		return rePassword;
	}

	public void setrePassword(String rePassword) {
		this.rePassword = rePassword;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	
	/**
	 * 用户注册
	 * @return	"loginSuccess":register.jsp
	 * 			"error":failure.jsp
	 * @throws Exception
	 */
	public String login() throws Exception
	{
		String e = ServletActionContext.getRequest().getParameter("email");
		String s = ServletActionContext.getRequest().getParameter("password");
		
		User user;
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String result="{";
		
		
		if(email != null && !email.equals(""))
		{
			if(password !=null && !password.equals(""))
			{
				try {
					user= userDAO.findById(email);
					if(user!=null)
					{
						if( DigestUtil.encrypt(password).equals(user.getPassword()))
						{
							ServletActionContext.getContext().getSession().put("user", user);
							errorMsg="";
							//result+="'errorMsg':''";
						//	return "loginSuccess";
						}else
						{
							errorMsg="输入密码不正确!";
						}
					}else
					{
						errorMsg="该账号不存在！";
					}
				} catch (Exception e1) {
					errorMsg="登录失败！请稍后重试。";
					log.error("login failed:"+e1.getMessage());
				}					
			}else
			{
				errorMsg="密码不能为空！ ";
			}
		}else
		{
			errorMsg ="邮箱不能为空！";
		}
		result+="'errorMsg':'"+errorMsg+"'}";
		out.println(result);
		out.flush();
		out.close();
		return NONE;
		//return ERROR;
		//return "loginFailure";
	}
	
	/**
	 * 退出登录，清空session
	 * @return	"logoutSuccess":index.jsp
	 */
	public String logout()
	{
		ServletActionContext.getContext().getSession().clear();
		return "logoutSuccess";
	}
	
	/**
	 * 用户注册
	 * @return "registerSuccess":regiter.jsp
	 * 		   "error":failure.jsp
	 * @throws IOException 
	 */
	public String register() throws IOException
	{
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String result="{";
		
		ServletActionContext.getContext().getSession().clear();
		if(email !=null && !email.trim().equals(""))
		{
			if(name != null && !name.trim().equals(""))
			{
				if(password !=null && !password.equals(""))
				{
					if(rePassword !=null && !rePassword.equals(""))
					{
						if(rePassword.equals(password))
						{
							if(phone !=null && !phone.trim().equals(""))
							{
								try {
									if(userDAO.findById(email) == null)//无相同注册邮箱
									{
										User user=new User(email, name, phone,DigestUtil.encrypt(password),qq);
										userDAO.save(user);
										//ServletActionContext.getContext().getSession().put("user", user);
										errorMsg="";
										//return "registerSuccess";
									}else
									{
										errorMsg ="该邮箱已注册！";
									}
								} catch (Exception e) 
								{
									errorMsg="注册失败！请重试。";
									log.error("register failed:"+e.getMessage());
								}
							}else
							{
								errorMsg="注册手机号不能为空!";
							}
						}else
						{
							errorMsg = "两次密码输入不一致！";
						}
					}else
					{
						errorMsg="确认密码不能为空！";
					}
				}else
				{
					errorMsg="注册密码不能为空！";
				}
			}else
			{
				errorMsg="用户名不能为空！";
			}
		}else
		{
			errorMsg = "注册邮箱不能为空！";
		}
		
		result+="'errorMsg':'"+errorMsg+"'}";
		out.println(result);
		out.flush();
		out.close();
		return NONE;
		//return "registerFailure";
		//return ERROR;
		
	}
	
	/**
	 * 用户信息更新
	 * 包括个人信息和密码更新
	 * 密码为空时不跟新密码，密码错误个人信息部进行更行
	 * @return
	 * @throws Exception
	 */
	public String update() throws Exception {
		User user = (User) ServletActionContext.getRequest().getSession().getAttribute("user");

		
		
		if (!password.equals("") && !newPassword.equals("") && !rePassword.equals("")) // 包括修改密码
		{
			if (newPassword.equals(rePassword)) 
			{
				if (DigestUtil.encrypt(password).equals(user.getPassword())) //密码校验
				{
					user.setName(name);
					user.setPhone(phone);
					user.setQq(qq);
					user.setPassword(DigestUtil.encrypt(newPassword));
					//userDAO.attachDirty(user);
					userDAO.update(user);
					ServletActionContext.getContext().getSession().put("user", user);
					return "updateSuccess";
				} else
				{
					throw new Exception("用户密码错误！");
				}
			} else 
			{
				throw new Exception("两次输入密码不一致！");
			}
		}else if(password.equals("") && newPassword.equals("") && rePassword.equals(""))//密码处没有值
		{
			user.setName(name);
			user.setPhone(phone);
			user.setQq(qq);
			//userDAO.attachDirty(user);
			userDAO.update(user);
			ServletActionContext.getRequest().getSession().setAttribute("user",user);
		}else
		{
			throw new Exception("密码修改填写不完整!");
		}
		
		
		return "updateSuccess";
	}
	
	public String checkUser() throws IOException
	{
		User user;
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String result="{";
		
		if(email!=null && !email.equals("")){
			user = userDAO.findById(email);
			if(user==null){
				errorMsg="";
			}else{
				errorMsg="邮箱已注册！";
			}
		}
		
		result+="'errorMsg':'"+errorMsg+"'}";
		out.println(result);
		out.flush();
		out.close();
		return NONE;
	}
	
}
